<template>
  <view class="login-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>

    <!-- 顶部状态栏 -->
    <view class="status-bar"></view>

    <!-- Logo区域 -->
    <view class="logo-section">
      <view class="logo-wrapper">
        <image 
          src="/static/logo.jpg" 
          mode="aspectFit" 
          class="logo"
        ></image>
        <view class="logo-ring"></view>
      </view>
      <text class="app-name">农药商城</text>
      <text class="app-slogan">专业农药，品质保证</text>
    </view>

    <!-- 登录表单 -->
    <view class="login-form">
      <!-- 标题 -->
      <view class="form-header">
        <text class="form-title">手机号登录</text>
        <text class="form-subtitle">输入手机号，获取验证码快速登录</text>
      </view>

      <!-- 手机号输入 -->
      <view class="input-group">
        <view class="input-item" :class="{ 'focused': phoneFocused, 'error': phoneError }">
          <view class="input-icon">
            <uni-icons type="phone" size="20" color="#667eea"></uni-icons>
          </view>
          <input 
            class="input-field"
            type="number" 
            placeholder="请输入手机号"
            v-model="phoneNumber"
            @focus="handlePhoneFocus"
            @blur="handlePhoneBlur"
            @input="handlePhoneInput"
            maxlength="11"
          />
          <view v-if="phoneNumber" class="clear-btn" @tap="clearPhone">
            <uni-icons type="closeempty" size="16" color="#999"></uni-icons>
          </view>
        </view>
        <view v-if="phoneError" class="error-text">{{ phoneError }}</view>

        <!-- 验证码输入 -->
        <view class="input-item" :class="{ 'focused': codeFocused }">
          <view class="input-icon">
            <uni-icons type="chatboxes" size="20" color="#667eea"></uni-icons>
          </view>
          <input 
            class="input-field"
            type="number"
            placeholder="请输入验证码"
            v-model="verifyCode"
            @focus="codeFocused = true"
            @blur="codeFocused = false"
            maxlength="6"
          />
          <button 
            class="code-btn" 
            :class="{ 'disabled': !canSendCode || codeSending }"
            @tap="sendVerifyCode"
            :disabled="!canSendCode || codeSending"
          >
            <text v-if="codeSending">发送中...</text>
            <text v-else-if="countdown > 0">{{ countdown }}s后重发</text>
            <text v-else>获取验证码</text>
          </button>
        </view>
      </view>

      <!-- 登录按钮 -->
      <button 
        class="login-btn" 
        :class="{ 'loading': isLogging, 'disabled': !canLogin }"
        @tap="handlePhoneLogin"
        :disabled="isLogging || !canLogin"
      >
        <view v-if="isLogging" class="loading-spinner"></view>
        <text>{{ isLogging ? '登录中...' : '登录' }}</text>
      </button>

      <!-- 分割线 -->
      <view class="divider">
        <text>或</text>
      </view>

      <!-- 微信登录 -->
      <button 
        class="wechat-btn" 
        :class="{ 'loading': wechatLogging }"
        @tap="handleWechatLogin"
        :disabled="wechatLogging"
        hover-class="wechat-btn-hover"
      >
        <view v-if="wechatLogging" class="loading-spinner white"></view>
        <uni-icons v-else type="weixin" size="20" color="#fff"></uni-icons>
        <text>{{ wechatLogging ? '微信登录中...' : '微信快速登录' }}</text>
      </button>
    </view>

    <!-- 用户协议 -->
    <view class="agreement-section">
      <view class="agreement-checkbox" @tap="toggleAgreement">
        <view class="checkbox" :class="{ 'checked': agreeToTerms }">
          <uni-icons v-if="agreeToTerms" type="checkmarkempty" size="12" color="#fff"></uni-icons>
        </view>
        <text class="agreement-text">
          我已阅读并同意
          <text class="link" @tap.stop="showTerms">《用户协议》</text>
          和
          <text class="link" @tap.stop="showPrivacy">《隐私政策》</text>
        </text>
      </view>
    </view>

    <!-- 微信授权测试入口 -->
    <view class="test-section">
      <text class="test-text">开发者测试：</text>
      <button 
        class="test-btn" 
        @tap="goToWechatTest"
        size="mini"
      >
        微信授权测试页面
      </button>
      <button 
        class="test-btn" 
        @tap="testJump"
        size="mini"
      >
        测试跳转
      </button>
    </view>

    <!-- 底部安全区域 -->
    <view class="bottom-safe"></view>
  </view>
</template>

<script>
import { phoneLogin, wechatLogin, sendSmsCode  } from '@/utils/auth'
import wechatAuth from '@/utils/wechat'

export default {
  data() {
    return {
      phoneNumber: '18712882023',
      verifyCode: '',
      phoneFocused: false,
      codeFocused: false,
      phoneError: '',
      agreeToTerms: true,
      isLogging: false,
      wechatLogging: false,
      codeSending: false,
      countdown: 0,
      timer: null
    }
  },

  computed: {
    // 是否可以发送验证码
    canSendCode() {
      return this.isValidPhone(this.phoneNumber) && this.countdown === 0
    },

    // 是否可以登录
    canLogin() {
      return this.isValidPhone(this.phoneNumber) && 
             this.verifyCode.length === 6 && 
             this.agreeToTerms
    },

    // 是否为微信小程序环境
    isWechatMiniProgram() {
      // #ifdef MP-WEIXIN
      return true
      // #endif
      // #ifndef MP-WEIXIN
      return false
      // #endif
    },

    // 是否为APP环境
    isApp() {
      // #ifdef APP-PLUS
      return true
      // #endif
      // #ifndef APP-PLUS
      return false
      // #endif
    },

    // 是否为H5环境
    isH5() {
      // #ifdef H5
      return true
      // #endif
      // #ifndef H5
      return false
      // #endif
    }
  },

  onLoad() {
    // 检查是否有保存的手机号
    const savedPhone = uni.getStorageSync('savedPhone')
    if (savedPhone) {
      this.phoneNumber = savedPhone
    }
    
    // 检查当前环境
    this.checkEnvironment()
  },

  onUnload() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },

  methods: {
    // 检查当前环境
    checkEnvironment() {
      // 环境信息检测，用于安全验证
      if (this.isWechatMiniProgram) {
        const accountInfo = uni.getAccountInfoSync()
        // 小程序环境
      } else if (this.isApp) {
        // APP环境
      } else {
        // H5环境
      }
    },

    // 手机号验证
    isValidPhone(phone) {
      const phoneReg = /^1[3-9]\d{9}$/
      return phoneReg.test(phone)
    },

    // 处理手机号焦点
    handlePhoneFocus() {
      this.phoneFocused = true
      this.phoneError = ''
    },

    // 处理手机号失焦
    handlePhoneBlur() {
      this.phoneFocused = false
      if (this.phoneNumber && !this.isValidPhone(this.phoneNumber)) {
        this.phoneError = '请输入正确的手机号'
      }
    },

    // 处理手机号输入
    handlePhoneInput(e) {
      this.phoneNumber = e.detail.value
      this.phoneError = ''
    },

    // 清除手机号
    clearPhone() {
      this.phoneNumber = ''
      this.phoneError = ''
    },

    // 发送验证码
    async sendVerifyCode() {
      if (!this.canSendCode) {
        return
      }

      if (!this.isValidPhone(this.phoneNumber)) {
        this.phoneError = '请输入正确的手机号'
        return
      }

      this.codeSending = true

      try {
        // 获取环境信息用于安全验证
        this.getEnvironmentInfo()
        
        const res = await sendSmsCode(this.phoneNumber)

        if (res.success || res.code === 200 || res.code === 0) {
          uni.showToast({
            title: '验证码已发送',
            icon: 'success'
          })
          this.verifyCode = res.code
          this.startCountdown()
        } else {
          throw new Error(res.message || '发送失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '发送验证码失败',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.codeSending = false
      }
    },

    // 开始倒计时
    startCountdown() {
      this.countdown = 60
      this.timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000)
    },

    // 手机号登录
    async handlePhoneLogin() {
      if (!this.canLogin) {
        if (!this.agreeToTerms) {
          uni.showToast({
            title: '请先同意用户协议',
            icon: 'none'
          })
        }
        return
      }
      this.isLogging = true
      try {
        const loginData = {
          phone: this.phoneNumber,
          verification_code: this.verifyCode,
          login_type: 'sms'
        }
        
        const success = await phoneLogin(loginData)
        if (success) {
          console.log('手机号登录成功，准备跳转...')
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })
          setTimeout(() => {
            console.log('开始跳转到首页...')
            uni.switchTab({
              url: '/src/pages/index/index',
              success: () => {
                console.log('跳转成功')
              },
              fail: (error) => {
                console.error('跳转失败:', error)
                // 如果switchTab失败，尝试使用reLaunch
                uni.reLaunch({
                  url: '/src/pages/index/index',
                  success: () => {
                    console.log('reLaunch跳转成功')
                  },
                  fail: (reLaunchError) => {
                    console.error('reLaunch也失败了:', reLaunchError)
                    uni.showToast({
                      title: '跳转失败，请手动返回首页',
                      icon: 'none'
                    })
                  }
                })
              }
            })
          }, 1500)
        } else {
          throw new Error('登录失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '登录失败，请检查手机号和验证码',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.isLogging = false
      }
    },

    // 微信登录
    async handleWechatLogin() {
      if (!this.agreeToTerms) {
        uni.showToast({
          title: '请先同意用户协议',
          icon: 'none'
        })
        return
      }

      try {
        this.wechatLogging = true

        // 先进行微信唤醒
        uni.showLoading({
          title: '唤醒微信中...'
        })
        
        try {
          await wechatAuth.wakeUpWechat()
          uni.hideLoading()
        } catch (wakeError) {
          uni.hideLoading()
          console.log('微信唤醒失败，继续尝试授权:', wakeError)
        }

        // 使用新的微信授权工具
        const result = await wechatAuth.login()
        
        if (result && result.success) {
          uni.showToast({
            title: '微信登录成功',
            icon: 'success'
          })
          
          // 显示微信用户信息
          if (result.wechatInfo) {
            console.log('微信用户信息:', result.wechatInfo)
            
            // 可以在这里显示用户信息
            const userInfo = result.wechatInfo.userInfo
            if (userInfo) {
              console.log('用户昵称:', userInfo.nickName)
              console.log('用户头像:', userInfo.avatarUrl)
              console.log('用户性别:', userInfo.gender)
              console.log('用户地区:', userInfo.country, userInfo.province, userInfo.city)
            }
          }
          
          setTimeout(() => {
            console.log('微信登录成功，开始跳转到首页...')
            uni.switchTab({
              url: '/src/pages/index/index',
              success: () => {
                console.log('微信登录跳转成功')
              },
              fail: (error) => {
                console.error('微信登录跳转失败:', error)
                // 如果switchTab失败，尝试使用reLaunch
                uni.reLaunch({
                  url: '/src/pages/index/index',
                  success: () => {
                    console.log('微信登录reLaunch跳转成功')
                  },
                  fail: (reLaunchError) => {
                    console.error('微信登录reLaunch也失败了:', reLaunchError)
                    uni.showToast({
                      title: '跳转失败，请手动返回首页',
                      icon: 'none'
                    })
                  }
                })
              }
            })
          }, 1500)
        } else {
          throw new Error('微信登录失败')
        }
      } catch (error) {
        console.error('微信登录错误:', error)
        uni.showToast({
          title: error.message || '微信登录失败',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.wechatLogging = false
      }
    },

    // 切换用户协议
    toggleAgreement() {
      this.agreeToTerms = !this.agreeToTerms
    },

    // 显示用户协议
    showTerms() {
      uni.showModal({
        title: '用户协议',
        content: '欢迎使用农药商城！\n\n1. 用户注册时需提供真实有效的信息\n2. 用户应妥善保管账号信息\n3. 用户不得从事违法违规活动\n4. 平台有权对违规行为进行处理\n5. 本协议解释权归平台所有',
        showCancel: false,
        confirmText: '我知道了'
      })
    },

    // 显示隐私政策
    showPrivacy() {
      uni.showModal({
        title: '隐私政策',
        content: '我们重视您的隐私保护！\n\n1. 我们收集的信息仅用于提供服务\n2. 不会向第三方泄露您的个人信息\n3. 采用加密技术保护数据安全\n4. 您有权查看、修改或删除个人信息\n5. 如有疑问请联系客服',
        showCancel: false,
        confirmText: '我知道了'
      })
    },

    getEnvironmentInfo() {
      // 环境信息检测，用于安全验证
      if (this.isWechatMiniProgram) {
        const accountInfo = uni.getAccountInfoSync()
        // 小程序环境
      } else if (this.isApp) {
        // APP环境
      } else {
        // H5环境
      }
    },

    // 快速跳转到微信授权测试页面
    goToWechatTest() {
      uni.navigateTo({
        url: '/pages/wechat-test/index'
      })
    },

    // 测试跳转功能
    testJump() {
      console.log('测试跳转功能...')
      uni.showToast({
        title: '测试跳转',
        icon: 'none'
      })
      
      setTimeout(() => {
        console.log('开始测试跳转到首页...')
        uni.switchTab({
          url: '/src/pages/index/index',
          success: () => {
            console.log('测试跳转成功')
            uni.showToast({
              title: '跳转成功',
              icon: 'success'
            })
          },
          fail: (error) => {
            console.error('测试跳转失败:', error)
            uni.showToast({
              title: '跳转失败: ' + JSON.stringify(error),
              icon: 'none',
              duration: 3000
            })
          }
        })
      }, 1000)
    }
  }
}
</script>

<style lang="scss">
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200rpx;
  height: 200rpx;
  top: 10%;
  right: -50rpx;
  animation-delay: 0s;
}

.circle-2 {
  width: 150rpx;
  height: 150rpx;
  top: 60%;
  left: -30rpx;
  animation-delay: 2s;
}

.circle-3 {
  width: 100rpx;
  height: 100rpx;
  top: 30%;
  left: 60%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20rpx);
  }
}

.status-bar {
  height: var(--status-bar-height);
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0 60rpx;
}

.logo-wrapper {
  position: relative;
  margin-bottom: 30rpx;
}

.logo {
  width: 140rpx;
  height: 140rpx;
  border-radius: 35rpx;
  background: rgba(255, 255, 255, 0.1);
  padding: 20rpx;
}

.logo-ring {
  position: absolute;
  top: -15rpx;
  left: -15rpx;
  width: 170rpx;
  height: 170rpx;
  border-radius: 50%;
  border: 3rpx solid rgba(255, 255, 255, 0.2);
  animation: pulse 3s infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.7;
  }
}

.app-name {
  font-size: 48rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 12rpx;
}

.app-slogan {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.8);
}

.login-form {
  background: #fff;
  margin: 0 40rpx;
  border-radius: 30rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
}

.form-header {
  text-align: center;
  margin-bottom: 60rpx;
}

.form-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #2D3748;
  margin-bottom: 12rpx;
  display: block;
}

.form-subtitle {
  font-size: 26rpx;
  color: #718096;
  display: block;
}

.input-group {
  margin-bottom: 50rpx;
}

.input-item {
  position: relative;
  display: flex;
  align-items: center;
  background: #F7FAFC;
  border: 2rpx solid transparent;
  border-radius: 16rpx;
  padding: 0 24rpx;
  margin-bottom: 30rpx;
  height: 96rpx;
  transition: all 0.3s ease;
}

.input-item.focused {
  background: #fff;
  border-color: #667eea;
  box-shadow: 0 0 0 8rpx rgba(102, 126, 234, 0.1);
}

.input-item.error {
  border-color: #E53E3E;
  background: #FFF5F5;
}

.input-icon {
  margin-right: 20rpx;
}

.input-field {
  flex: 1;
  font-size: 30rpx;
  color: #2D3748;
  background: transparent;
  border: none;
  outline: none;
}

.input-field::placeholder {
  color: #A0AEC0;
}

.clear-btn {
  padding: 10rpx;
  cursor: pointer;
}

.code-btn {
  padding: 16rpx 24rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: #fff;
  border-radius: 12rpx;
  font-size: 24rpx;
  font-weight: 500;
  border: none;
  white-space: nowrap;
  transition: all 0.3s ease;
}

.code-btn.disabled {
  background: #E2E8F0;
  color: #A0AEC0;
}

.code-btn::after {
  border: none;
}

.error-text {
  font-size: 24rpx;
  color: #E53E3E;
  margin-top: -20rpx;
  margin-bottom: 20rpx;
  margin-left: 24rpx;
}

.login-btn {
  width: 100%;
  height: 96rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 48rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 30rpx rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
  margin-bottom: 40rpx;
  position: relative;
  overflow: hidden;
}

.login-btn:active {
  transform: scale(0.98);
}

.login-btn.disabled,
.login-btn.loading {
  background: #CBD5E0;
  box-shadow: none;
  color: #A0AEC0;
}

.login-btn::after {
  border: none;
}

.divider {
  position: relative;
  text-align: center;
  margin: 40rpx 0;
  
  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 1rpx;
    background: #E2E8F0;
  }
  
  text {
    background: #fff;
    padding: 0 20rpx;
    font-size: 24rpx;
    color: #718096;
  }
}

.wechat-btn {
  width: 100%;
  height: 96rpx;
  background: linear-gradient(135deg, #07C160, #06AD56);
  color: #fff;
  font-size: 30rpx;
  font-weight: 600;
  border-radius: 48rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  box-shadow: 0 8rpx 30rpx rgba(7, 193, 96, 0.3);
  transition: all 0.3s ease;
}

.wechat-btn:active {
  transform: scale(0.98);
}

.wechat-btn.loading {
  background: #CBD5E0;
  box-shadow: none;
}

.wechat-btn::after {
  border: none;
}

.wechat-btn-hover {
  opacity: 0.8;
  transform: scale(0.98);
}

.loading-spinner {
  width: 32rpx;
  height: 32rpx;
  border: 3rpx solid rgba(255, 255, 255, 0.3);
  border-top: 3rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-right: 12rpx;
}

.loading-spinner.white {
  border-top-color: #fff;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.agreement-section {
  padding: 13%;
}

.agreement-checkbox {
  display: flex;
  align-items: flex-start;
}

.checkbox {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid rgba(255, 255, 255, 0.5);
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  margin-top: 2rpx;
}

.checkbox.checked {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-color: #667eea;
}

.agreement-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.5;
  margin-left: 12rpx;
  
  .link {
    color: #FFD93D;
    text-decoration: underline;
  }
}

.test-section {
  padding: 13%;
  text-align: center;
}

.test-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 20rpx;
}

.test-btn {
  padding: 16rpx 24rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: #fff;
  border-radius: 12rpx;
  font-size: 24rpx;
  font-weight: 500;
  border: none;
  white-space: nowrap;
  transition: all 0.3s ease;
}

.bottom-safe {
  height: env(safe-area-inset-bottom);
  height: constant(safe-area-inset-bottom);
}
</style> 